﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Security;
using System.Windows.Forms;
using Autofac;
using ComputerVision.BaseForm;
using ComputerVision.Data;
using ComputerVision.Services;

namespace ComputerVision.Role
{
    public partial class frmUserInRole : frmObject
    {
        private readonly IService<aspnet_Users> _users;
        private string _roleName;
        public frmUserInRole()
        {
            InitializeComponent();
            _users = Program.Container.Resolve<IService<aspnet_Users>>();
        }

        private void LoadListRole()
        {
            var arrRole = Roles.GetAllRoles();
            foreach (var s in arrRole)
            {
                lstViewRole.Items.Add(s);
            }
        }

        private void frmUserInRole_Load(object sender, EventArgs e)
        {
            LoadListRole();
        }

        #region GetUsersInRole
        private void GetUserInRole()
        {
            var lstUsers = new List<aspnet_Users>();
            var selectedItems = lstViewRole.SelectedItems;
            if (selectedItems.Count > 0)
            {
                var lstUser = Roles.GetUsersInRole(selectedItems[0].Text);
                _roleName = selectedItems[0].Text;
                foreach (var userName in lstUser)
                {
                    var user = _users.ToList().FirstOrDefault(p => p.UserName == userName);
                    if (user != null)
                    {
                        lstUsers.Add(user);
                    }
                }
                aspnetUsersBindingSource.DataSource = lstUsers;
            }
        }

        private void lstViewRole_SelectedIndexChanged(object sender, EventArgs e)
        {
            GetUserInRole();
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            GetUserInRole();
        }
        #endregion

        private void btnSelectUser_Click(object sender, EventArgs e)
        {
            var frm = new frmSelectUser(_roleName);
            frm.ShowDialog();
            GetUserInRole();
        }

        private void btnRemoveUserInRole_Click(object sender, EventArgs e)
        {
            int count = dgvUsers.Rows.GetRowCount(DataGridViewElementStates.Selected);
            if (count>0)
            {
                for (int i = 0; i < count; i++)
                {
                    Roles.RemoveUserFromRole(dgvUsers.SelectedRows[i].Cells[1].Value.ToString(),_roleName); 
                }
            }
            GetUserInRole();
        }

        
    }
}